//
//  CJBZNativeAdapter.m
//  Pods
//
//  Created by shanghailingye on 2025/10/20.
//

#import "CJBZNativeAdapter.h"
#import "CJBZNativeExpressView.h"

@interface CJBZNativeAdapter()<CJNativeAdDelegate>

@property (nonatomic, strong) CJNativeAd *nativeExpressAd;

@property (nonatomic, assign) BOOL isBiddingRequest;

@property (nonatomic, strong) AMPSAdConfiguration *adConfiguration;

@property (nonatomic, strong) CJBZNativeExpressView *lingyeNativeExpressView;

@end

@implementation CJBZNativeAdapter

- (void)requestBiddingPriceWithSpaceId:(NSString *)spaceId
                       adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    self.isBiddingRequest = YES;
    [self loadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
}

- (void)loadAdWithSpaceId:(nonnull NSString *)spaceId adConfiguration:(nonnull AMPSAdConfiguration *)adConfiguration {
    if (CJBZSDKManagerAdapter.initState != kAdScopeMediationAdapterInitSDKStateSuccess) {
        __weak typeof(self)weakSelf = self;
        [CJBZSDKManagerAdapter startAsyncWithAppId:self.appId configuration:self.sdkConfiguration results:^(BOOL adapterResult) {
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (adapterResult) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self lingYeLoadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
                });
            } else {
                if (strongSelf.isBiddingRequest) {
                    NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:250401 userInfo:@{@"NSLocalizedDescription": @"AMPSGDTSDKManagerAdapter init fail"}];
                    if (strongSelf.bidDelegate && [strongSelf.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
                        [strongSelf.bidDelegate requestBiddingPriceFail:strongSelf error:error ext:adConfiguration.ext];
                    }
                } else {
                    NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:270401 userInfo:@{@"NSLocalizedDescription": @"AMPSGDTSDKManagerAdapter init fail"}];
                    if (strongSelf.customDelegate && [strongSelf.customDelegate respondsToSelector:@selector(nativeAdManagerLoadFail:error:ext:)]) {
                        [strongSelf.customDelegate nativeAdManagerLoadFail:strongSelf error:error ext:adConfiguration.ext];
                    }
                }
            }
        }];
    } else {
        [self lingYeLoadAdWithSpaceId:spaceId adConfiguration:adConfiguration];
    }
}

- (void)lingYeLoadAdWithSpaceId:(NSString *)spaceId adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    self.nativeExpressAd = [[CJNativeAd alloc] initWithSlotId:spaceId size:adConfiguration.adSize rootViewController:adConfiguration.viewController];
    self.nativeExpressAd.delegate = self;
    self.adConfiguration = adConfiguration;
    [self.nativeExpressAd loadAdData: 1];
}

- (void)removeAd {
    if (_viewsArray) {
        _viewsArray = nil;
    }
    if (_nativeExpressAd) {
        if ([_nativeExpressAd respondsToSelector:@selector(delegate)]) {
            _nativeExpressAd.delegate = nil;
        }
        _nativeExpressAd = nil;
    }
}

- (BOOL)isValid {
    return YES;
}

- (void)loadC2SAdWithSpaceId:(NSString *)spaceId
                biddingToken:(id)biddingToken
             adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    if (self.isLoadAdSuccess) {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadSuccess:ext:)]) {
            [self.customDelegate nativeAdManagerLoadSuccess:self ext:self.adConfiguration.ext];
        }
    }
}

- (void)loadS2SAdWithSpaceId:(NSString *)spaceId
                biddingToken:(id)biddingToken
             adConfiguration:(AMPSAdConfiguration *)adConfiguration {
    
}


- (void)nativeExpressAdDidLoad:(id)nativeExpressAd views:(NSArray *)nativeExpressViews {
    NSMutableArray *nativeAdViewArr = [NSMutableArray array];
    NSInteger ecpm = [nativeExpressAd getECpm];
    CJBZNativeExpressView *lingyeNativeExpressView = [[CJBZNativeExpressView alloc] init];
    lingyeNativeExpressView.isLoadSuccess = true;
    lingyeNativeExpressView.ecpm = ecpm;
    [lingyeNativeExpressView addSubview:self.nativeExpressAd.adView];
    [lingyeNativeExpressView layoutIfNeeded];
    NSLog(@"frame---%@", self.nativeExpressAd.adView);
    lingyeNativeExpressView.frame = self.nativeExpressAd.adView.frame;
    self.lingyeNativeExpressView = lingyeNativeExpressView;
    [nativeAdViewArr addObject:lingyeNativeExpressView];
    self.viewsArray = [NSArray arrayWithArray:nativeAdViewArr];
    self.isLoadAdSuccess = YES;
    if (!self.isBiddingRequest) {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadSuccess:ext:)]) {
            [self.customDelegate nativeAdManagerLoadSuccess:self ext:self.adConfiguration.ext];
        }
        return;
    }
    if (ecpm > 0) {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceSuccess:ext:)]) {
            [self.bidDelegate requestBiddingPriceSuccess:self ext:self.adConfiguration.ext];
        }
    } else {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
            NSError *error = [NSError errorWithDomain:@"xyz.adscope.MediationErrorDomain" code:250401 userInfo:@{@"NSLocalizedDescription": @"AMPSGDTNativeExpressAdapter ad bidding fail,ecpm less than 0"}];
            [self.bidDelegate requestBiddingPriceFail:self error:error ext:self.adConfiguration.ext];
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (lingyeNativeExpressView.viewDelegate && [lingyeNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewRenderSuccess:ext:)]) {
            [lingyeNativeExpressView.viewDelegate nativeViewRenderSuccess:lingyeNativeExpressView ext:self.adConfiguration.ext];
        }
    });
}

- (void)nativeExpressAdLoadFailed:(id)nativeExpressAd error:(NSError *)error {
    if (self.isBiddingRequest) {
        if (self.bidDelegate && [self.bidDelegate respondsToSelector:@selector(requestBiddingPriceFail:error:ext:)]) {
            [self.bidDelegate requestBiddingPriceFail:self error:error ext:self.adConfiguration.ext];
        }
    } else {
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(nativeAdManagerLoadFail:error:ext:)]) {
            [self.customDelegate nativeAdManagerLoadFail:self error:error ext:self.adConfiguration.ext];
        }
    }
    [self removeAd];
}

- (void)nativeExpressAdOnShow:(id)nativeExpressView {
    if (self.lingyeNativeExpressView.viewDelegate && [self.lingyeNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewExposured:)]) {
        [self.lingyeNativeExpressView.viewDelegate nativeViewExposured:self.lingyeNativeExpressView];
    }
}

- (void)nativeExpressAdOnClicked:(id)nativeExpressView {
    if (self.lingyeNativeExpressView.viewDelegate && [self.lingyeNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewDidClick:)]) {
        [self.lingyeNativeExpressView.viewDelegate nativeViewDidClick:self.lingyeNativeExpressView];
    }
}

- (void)nativeExpressAdOnClosed:(id)nativeExpressView {
    if (self.lingyeNativeExpressView.viewDelegate && [self.lingyeNativeExpressView.viewDelegate respondsToSelector:@selector(nativeViewDidClose:)]) {
        [self.lingyeNativeExpressView.viewDelegate nativeViewDidClose:self.lingyeNativeExpressView];
    }
    [self removeAd];
}


- (void)dealloc {
    [self removeAd];
}


@end
